package cn.time1024.time_app.ui.notifications

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.navigation.fragment.findNavController
import cn.time1024.time_app.databinding.FragmentNotificationCenterBinding
import com.example.timeassistant.network.ApiService
import com.example.timeassistant.network.ResponseEnvelope
import com.example.timeassistant.network.RetrofitClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class NotificationCenterFragment : Fragment() {

    private var _binding: FragmentNotificationCenterBinding? = null
    private val binding get() = _binding!!

    /**
     * 创建通知中心页面视图，当前为占位展示文本。
     */
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentNotificationCenterBinding.inflate(inflater, container, false)
        setupList()
        setupRefresh()
        loadPage(reset = true)
        return binding.root
    }

    /**
     * 销毁视图绑定，避免内存泄漏。
     */
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private lateinit var adapter: NotificationsAdapter
    private var pageNo = 1
    private var pageSize = 10
    private var isLoading = false
    private var hasMore = true

    /** 初始化列表 */
    private fun setupList() {
        adapter = NotificationsAdapter(mutableListOf()) { item: ApiService.NotificationItem ->
            val bundle = android.os.Bundle().apply {
                putLong("notificationId", item.notificationId ?: 0L)
                putString("title", item.title)
                putString("type", item.type)
            }
            findNavController().navigate(cn.time1024.time_app.R.id.navigation_notification_detail, bundle)
        }
        binding.rvNotifications.layoutManager = LinearLayoutManager(requireContext())
        binding.rvNotifications.adapter = adapter
    }

    /** 下拉刷新 */
    private fun setupRefresh() {
        binding.swipeRefresh.setOnRefreshListener { loadPage(reset = true) }
    }

    /** 加载分页 */
    private fun loadPage(reset: Boolean) {
        if (isLoading) return
        isLoading = true
        if (reset) { pageNo = 1; hasMore = true }
        RetrofitClient.api.getNotificationsPage(pageNo = pageNo, pageSize = pageSize)
            .enqueue(object: Callback<ResponseEnvelope<ApiService.PageResult<ApiService.NotificationItem>>> {
                override fun onResponse(
                    call: Call<ResponseEnvelope<ApiService.PageResult<ApiService.NotificationItem>>>,
                    response: Response<ResponseEnvelope<ApiService.PageResult<ApiService.NotificationItem>>>
                ) {
                    isLoading = false
                    binding.swipeRefresh.isRefreshing = false
                    val data = response.body()?.data
                    val list = data?.rows ?: emptyList()
                    if (reset) adapter.replaceAll(list) else adapter.appendAll(list)
                    val total = data?.totalRows ?: list.size
                    hasMore = (adapter.itemCount < total)
                    if (hasMore) pageNo += 1
                }
                override fun onFailure(
                    call: Call<ResponseEnvelope<ApiService.PageResult<ApiService.NotificationItem>>>,
                    t: Throwable
                ) {
                    isLoading = false
                    binding.swipeRefresh.isRefreshing = false
                }
            })
    }
}